package com.bookbuf.social.share.content.media.image.converter;

import android.graphics.Bitmap;
import android.util.Log;

import com.bookbuf.social.secure.AesHelper;
import com.bookbuf.social.share.content.media.image.util.BitmapUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Created by robert on 16/7/4.
 */
public class BitmapConverter extends ConfiguredConverter {
	private Bitmap bitmap;

	public BitmapConverter (Bitmap bitmap) {
		this.bitmap = bitmap;
	}

	public File asFile () {
		FileOutputStream outputStream = null;

		try {
			long currentTimeMillis = System.currentTimeMillis ();
			File file = this.getConfig ().generateCacheFile (AesHelper.md5 (this.bitmap.toString ()));
			outputStream = new FileOutputStream (file);
			int var5 = this.bitmap.getRowBytes () * this.bitmap.getHeight () / 1024;
			Log.d ("", "### bitmap size = " + var5 + " KB");
			int var6 = 100;
			if ((float) var5 > this.getConfig ().mImageSizeLimit) {
				var6 = (int) (this.getConfig ().mImageSizeLimit / (float) var5 * (float) var6);
			}

			Log.d ("", "### 压缩质量 : " + var6);
			if (!this.bitmap.isRecycled ()) {
				this.bitmap.compress (Bitmap.CompressFormat.JPEG, var6, outputStream);
			}

			Log.d ("", "##save bitmap " + file.getAbsolutePath ());
			long var7 = System.currentTimeMillis ();
			Log.d ("", "#### 图片序列化耗时 : " + (var7 - currentTimeMillis) + " ms.");
			return file;
		} catch (Exception e) {
			Log.e ("", "Sorry cannot setImage..[" + e.toString () + "]");
		} finally {
			if (outputStream != null) {
				try {
					outputStream.close ();
				} catch (IOException e) {
					e.printStackTrace ();
				}
			}
		}
		return null;
	}

	public String asUrl () {
		return null;
	}

	public byte[] asBinary () {
		return BitmapUtils.bitmap2Bytes (this.bitmap);
	}

	public Bitmap asBitmap () {
		return this.bitmap;
	}
}
